<?php
session_start();

include_once("db_connection.php");
include_once("Product_Operation.php");
include_once("Category_Operation.php");
include_once("auth_process.php");

$authResult = validateSession();

if ($authResult['result'] == false) {
    //reject the operation
    header("Location: login.php");
    exit();
}

function operate_db($db_Operation)
{
    try {
        $conn = getdb();
        return $db_Operation->operate($conn);

    } catch (Exception $exception) {
        throw $exception;
    } finally {
        $conn = null;
    }
}

function ierg4210_add_product()
{
    return operate_db(new Insert_Product());
}

function ierg4210_update_product()
{
    return operate_db(new Update_Product());
}

function ierg4210_delete_product()
{
    return operate_db(new Delete_Product());
}

function ierg4210_add_category()
{
    return operate_db(new Insert_Category());
}

function ierg4210_update_category()
{
    return operate_db(new Update_Category());
}

function ierg4210_delete_category()
{
    return operate_db(new Delete_Category());
}

?>

<?php

if (isset($_POST['action'])) {

    header('Content-Type: application/json');

    if (!isset($_POST['manage_token']) || $_POST['manage_token'] != $_SESSION['manage_token']) {
        echo json_encode(array('failed' => 'invalid manage token'));
        exit();
    }

    try {
        // To call the corresponding function based on action name
        $returnVal = call_user_func('ierg4210_' . $_POST['action']);
        if ($_POST['action'] == 'update_product') {
            header("HTTP/1.1 200 OK");
            echo json_encode(array("success" => $returnVal));
        } else {
            header("Location: shop_manage.php");
        }
        exit();
    } catch (Exception $e) {
        header("HTTP/1.1 400");
        echo json_encode(array('failed' => "Operation Fail! Error: " . $e->getMessage()));
    }
} else {
    header("HTTP/1.1 400");
    echo json_encode(array('failed' => 'undefined action'));
    exit();
}
?>
